require 'MVVM.Sources.View.Adaptor'

FancyScrollAdaptor = class('FancyScrollAdaptor', Adaptor)

function FancyScrollAdaptor:ctor(gameObject, propertyName, binder,centerItemIndex,scrollIndex)
    self.FancyScroll =gameObject:GetComponent('UnityEngine.UI.Extensions.LuaScrollView')
    self.Scroller =gameObject:GetComponent('UnityEngine.UI.Extensions.ScrollPositionController')
    self.startPos = 0
    if centerItemIndex then
        binder:Add(centerItemIndex,function(oldValue,newValue)
            if newValue == nil or  oldValue == newValue then
                return
            end
            self.startPos = newValue
        end)
    end

    self:BindProperty(propertyName, binder)
    binder:RegisterEvent(function(viewModel, property)
        self.Scroller:OnItemSelected(function(index)
            viewModel:SetSelect(index)
        end)
    end, function()
        self.Scroller:OnItemSelected(nil)
    end, propertyName)

    if scrollIndex then
        binder:Add(scrollIndex,function(oldValue,newValue)
            if newValue == nil or  oldValue == newValue then
                return
            end

            self.FancyScroll:SelectCell(newValue)
        end)
    end

end

function FancyScrollAdaptor:OnViewModelValueChanged(oldValue, newValue)
    if newValue == nil then
        return
    end
    self.items = {}
    for i = 1, #newValue do
        local data =  UnityEngine.UI.Extensions.FancyLuaCellData.New()
        data.index = i
        data.luaData = newValue[i]
        table.insert(self.items,data)
    end
    self.FancyScroll:UpdateData(self.items)

    self.Scroller:JumpToCircular(self.startPos)
end